#include "contact_info.h"
#include "userobject.h"

#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>

Contact_Info::Contact_Info(Http_Post *parent) :
	Http_Post(parent)
{

}

Contact_Info::~Contact_Info()
{

}

void Contact_Info::m_clear()
{
	Q_FOREACH (QObject* obj, m_contactList) {
		if (obj) {
			delete obj;
			obj = Q_NULLPTR;
		}
	}
	m_contactList.clear();
}

void Contact_Info::m_post(QString host)
{
	m_clear();

	QString url = host + WX_CGI_PATH + "webwxgetcontact?r=" +
		QString::number(time(NULL));
#if QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << url;
#endif
	QString json = "{}";
	Http_Post::post(url, json, true);
}

void Contact_Info::postV2()
{
	m_post(WX_V2_SERVER_HOST);
}

void Contact_Info::finished(QNetworkReply* reply)
{
	QString replyStr(reply->readAll());

#if QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
	//qDebug() << "DEBUG:" << replyStr;
	QFile file("contact.json");
	if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		QTextStream out(&file);
		out << replyStr;
		file.close();
	}
#endif

	QJsonDocument doc = QJsonDocument::fromJson(replyStr.toUtf8());
	if (!doc.isObject()) {
		Q_EMIT error();
		return;
	}

	QJsonObject obj = doc.object();
	QJsonObject ret = obj["BaseResponse"].toObject();
	if(ret["Ret"].toString() != 0) {
		Q_EMIT error();
		return;
	}

	QJsonArray arr = obj["MemberList"].toArray();

	m_contactList.append(new UserObject("groupsend", tr("Group Send"), ""));
	Q_FOREACH (const QJsonValue & val, arr) {
		QJsonObject user = val.toObject();

		QString userName = user["UserName"].toString();
		QString nickName = user["NickName"].toString();

		if (!m_map.contains(userName)) {
			m_map.insert(userName, nickName);
			m_contactList.append(new UserObject(userName, nickName, WX_V2_SERVER_HOST + user["HeadImgUrl"].toString()));
		}
	}

	qDebug() << "DEBUG:count:" << m_contactList.count();

	Q_EMIT contact_ok();
}

QString Contact_Info::getNickName(QString userName)
{
	for (QObject* obj : m_contactList) {
		UserObject* contact = qobject_cast<UserObject*>(obj);
		if (contact->userName() == userName)
			return contact->nickName();
	}
	return "";
}

QString Contact_Info::getHeadImgUrl(QString userName)
{
	for (QObject* obj : m_contactList) {
		UserObject* contact = qobject_cast<UserObject*>(obj);
		if (contact->userName() == userName)
			return contact->headImgUrl();
	}
	return "";
}
